package com.caiyi.financial.nirvana.sms.gateway;

import com.alibaba.fastjson.JSON;
import com.caiyi.financial.nirvana.sms.entity.SmsGateway;
import com.caiyi.financial.nirvana.sms.enums.SmsGatewayProtocolEnum;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp20.CMPPClient;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp30.CMPP3Client;
import com.caiyi.financial.nirvana.sms.gateway.http.BaseGateway;
import com.caiyi.financial.nirvana.sms.gateway.sgip.SGIPClient;
import com.caiyi.financial.nirvana.sms.gateway.sgip.SGIPServerManager;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 通道控制器
 */
public class Controller {

    private static final Logger logger = LoggerFactory.getLogger(Controller.class);

    // 所有通道列表
    private final static Map<Integer, GateWayThread<? extends DefaultGateWay>> gateWays = new ConcurrentHashMap<>();

    /**
     * 获取当前所有的通道
     *
     * @return
     */
    public static Map<Integer, GateWayThread<? extends DefaultGateWay>> getCurrentGateWay() {
        return gateWays;
    }

    /**
     * 新增通道网关
     *
     * @param gateWayId
     * @param gate
     */
    public static void addGateWayThread(int gateWayId, GateWayThread<? extends DefaultGateWay> gate) {
        if (gateWays.containsKey(gateWayId)) {
            logger.error("add gateway thread error, already have gateway thread!");
            GateWayThread<? extends DefaultGateWay> gwt = gateWays.get(gateWayId);
            gwt.kill();
        }
        gateWays.put(gateWayId, gate);
    }

    /**
     * 获取通道网关
     *
     * @param gateWayId
     * @return GateWay
     */
    public static GateWayThread<? extends DefaultGateWay> getGateWayThread(int gateWayId) {
        return gateWays.get(gateWayId);
    }

    /**
     * 删除通道网关线程
     *
     * @param gatewayId
     */
    public static void removeGateWayThread(int gatewayId) {
        GateWayThread<? extends DefaultGateWay> gateWayThread = getGateWayThread(gatewayId);
        if (gateWayThread == null) {
            return;
        }
        gateWayThread.kill();
        gateWays.remove(gatewayId);
    }

    /**
     * 初始化网关
     */
    public static void initGateWay(int gId) {
        logger.info("初始化网关开始:" + gId);
        String key = String.format(JedisKey.SMS_GATEWAY, gId);
        SmsGateway entity = JSON.parseObject(JedisService.get(key), SmsGateway.class);
        if (entity != null) {
            initGateWayItem(entity);
        }
    }

    /**
     * 初始化网关
     */
    public static void initGateWay() {
        Set<String> gatewayKeys = JedisService.keys(String.format(JedisKey.SMS_GATEWAY, "*"));
        Iterator<String> iterator = gatewayKeys.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            SmsGateway entity = JSON.parseObject(JedisService.get(key), SmsGateway.class);
            initGateWayItem(entity);
        }
    }

    private static DefaultGateWay createGateway(int protocol, String code) {
        if (protocol == SmsGatewayProtocolEnum.HTTP.index) {
            return BaseGateway.getGateway(code);
        } else if (protocol == SmsGatewayProtocolEnum.CMPP3.index) {
            return new CMPP3Client();
        } else if (protocol == SmsGatewayProtocolEnum.SGIP.index) {
            return new SGIPClient();
        } else if (protocol == SmsGatewayProtocolEnum.CMPP2.index) {
            return new CMPPClient();
        }
        return null;
    }

    /**
     * 初始化网关
     *
     * @throws InterruptedException
     */
    private static void initGateWayItem(SmsGateway info) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                DefaultGateWay gateWay = createGateway(info.getProtocol(), info.getCode());
                if (gateWay != null) {
                    try {
                        logger.info("初始化网关：" + info.getName());
                        gateWay.init(info);
                        gateWay.start();
                        logger.info("网关线程开始，等待发送");
                        GateWayThread<DefaultGateWay> gateWayThread = new GateWayThread(info.getName(), gateWay);
                        gateWayThread.start();
                        addGateWayThread(info.getId(), gateWayThread);
                        SGIPServerManager.getInstance().push(gateWay);
                    } catch (InterruptedException ex) {
                        logger.error(ex.getMessage(), ex);
                        return;
                    }
                }
            }
        }).start();
    }

    /**
     * 关闭所有网关进程
     *
     * @throws InterruptedException
     */
    public static void stopGateways() {
        Set<Entry<Integer, GateWayThread<? extends DefaultGateWay>>> gateWaySet = gateWays.entrySet();
        GateWayThread<?> thread = null;
        try {
            for (Entry<Integer, GateWayThread<? extends DefaultGateWay>> entity : gateWaySet) {
                thread = entity.getValue();
                thread.kill();
            }
        } catch (Exception e) {
            logger.error("gateway stop error : " + thread);
        }

    }

}
